<?php
class keywordModule extends Module {
	/**
	 * callback调用
	 * 20170802 加入了$message->indMediaId媒体平台值
	 */
	public function run($message, $material, $status) {
		if ($message->msgType != message_type_text) {
			Log::write("不是文本不处理");
			return NULL;
		}
		
		//$keys = explode(' ', $message->content);
		$keys = trim($message->content);
		$arr_material = $this->exist($keys, $message->indMediaId);
//		$material = $this->exist($keys);
        /**
            {
                "id": "338",
                "name": "",
                "module": "text",
                "xml": "<xml><content><![CDATA[ll6-7]]></content><description><![CDATA[]]></description></xml>",
                "groupId": "0",
                "updateTime": "2017-07-18 15:00:24",
                "deleted": "0",
                "accessTag": "",
                "readCount": "5",
                "moduleId": null,
                "media_id": null,
                "type": "text",
                "lockStatus": "0",
                "lockTime": null
            }
         */
        // TODO: 现在返回一个数组了

        $arr_result = [];
        foreach ($arr_material as $k => $material) {

//        // 这里原来就是注释的
//		if (!isset($material)) {
//			// 找不到关键字判断是否是带参数的关键字
//			$result = $this->existWithParam($message);
//			if (isset($result)) {
//				return $result;
//			}
//
//			Log::write("找不到关键字不处理");
//			return NULL;
//		}
		
            $material = (object)$material;
            Log::write("找到关键字:$message->content, 使用$material->module 处理");
//		switch($material->module){
//			case "messageSearch":
//				$us = UserStatus::create($message->fromUserName, $material->id);
//				$us->status=2;
//				UserStatus::begin($us);
//				return $this->actionMaterial($material, $message,$us);
//				break;
//		}
            $readCount = $material->readCount + 1;
            $materialModel = m("material");
            $readCountData['readCount'] = $readCount;
            $materialModel->where("id = {$material->id}")->save($readCountData);

            /**
                {
                    "content": "ll6-7",
                    "fromUserName": "gh_e86a027dc440",
                    "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                    "createTime": 1500388598,
                    "msgType": "text",
                    "funcFlag": 0
                }
             */
            $result = $this->actionMaterial($material, $message);

            array_push($arr_result, $result);
        }

        return $arr_result;
	}
	
	/*
	 * 调用插件资源
	*/
	public function call($user, $method, $param) {
		switch ($method) {
			case 'exist':
				return $this->exist($param->keyword, $param->message->indMediaId);
			case 'action': 
				return $this->action($param->keyword, $param->message);
			case 'sendNewsCode':
				$this->sendNewsCode($param);
				break;
		}
	}
	private function existWithParam($message) {
		$content = $message->content;
		$customerId = Session::$user["customerId"];
		$sql = "select * from (select *,LOCATE(`content`,'$content') as paramIndex from`wx_" . $customerId 
			. "_material_keyword_with_param` where deleted = 0 AND content <> '') as paramTable where paramIndex = 1;";
		$model = new Model();
		$result = $model->query($sql);
// 		echo $model->getLastSql();
		if (!$result) {
			return;
		}
		
		$result = $result[0];
		$keyword = $result["keyword"];
		$material = $this->exist($keyword, $message->indMediaId);
		if (!isset($material)) {
			return;
		}
		
		$material = (object)$material;
		$module = $material->module;
		Log::write("找到关键字:$keyword, 使用$module 处理");

		$us = UserStatus::create($message->fromUserName, $material->id);
		UserStatus::begin($us);

		$moduleError = false;
		switch ($module) {
			case module_handle_inviteCodeInput:
			case module_handle_red_envelope:
			case module_handle_pushMsg:
				$us->status = '1';
				$contentNew = substr($content, strlen($result["content"]));
				$message->content = $contentNew;
				break;
			case "messageSearch":
				$us->status = '2';
				break;
			default:
				$moduleError = true;
				break;
		}
		if ($moduleError) {
			UserStatus::end($us);
			return;
		}
		
		UserStatus::update($us);
		return Module::doModule($module, $message, $material, $us);
	}

    /**
     * 消息互动 - 扫描二维码时, 通过qrcode-Module调入
     * @param $param
     */
	private function sendNewsCode($param){
		$keyword = $param->keyword;
		$message = $param->message;
//		$material = (object)$this->exist($keyword);
        $arr_material = $this->exist($keyword, $message->indMediaId);

        foreach ($arr_material as $k => $material) {
            $material = (object)$this->exist($keyword, $message->indMediaId);

            $materialObj = simplexml_load_string($material->xml,
                'SimpleXMLElement', LIBXML_NOCDATA);
            $articles = array();
            $articlesXml = $materialObj->Articles;

            foreach($articlesXml->item as $key=>$value){
                $article=new stdClass();
                $article->title = urlencode((string)$value->title);
                $article->url = urlencode((string)$value->url);
                $article->picurl = urlencode((string)$value->picUrl);
                $article->description = urlencode((string)$value->description);
                array_push($articles, $article);
            }
            WeixinApi::sendServiceMsg($message->fromUserName, 'news','',$articles);
        }
	}

	private function exist($keyword, $indMediaId = 0) {
		$keywordModel = M("Material_keyword");
		$materialModel = M("Material");
		
		// $where['keyword'] = array('LIKE', "$keyword%");
		$whereOr['_string'] = "'$keyword' LIKE concat('%', keyword, '%')";
		$whereOr['_logic'] = "and";
		$where['_complex'] = $whereOr;
		$where['exactMatch'] = 0;
		$map['_complex'] = $where;
		$map['_string'] = "keyword = '$keyword' AND exactMatch = 1";
		$map['_logic'] = "or";
		$condition['_complex'] = $map;
		$condition['_string'] = 'deleted=0';
		$condition['_logic'] = "and";
        if ($indMediaId > 0) { // 区分自媒体平台
            $indMediaIdWhere['_complex'] = $condition;
            $indMediaIdWhere['_string'] = 'mediaId=' . $indMediaId;
            $indMediaIdWhere['_logic'] = "and";
        } else {
            $indMediaIdWhere = $condition;
        }

		$sql = $keywordModel->field('materialId')->where($indMediaIdWhere)->select(false);
		$mmap['_string'] = "id IN ( $sql )";
		$result = $materialModel->where($mmap)->select();
//		$result = $materialModel->where($mmap)->find();
        /**
         * SELECT *
         * FROM `wx_3_material`
         * WHERE ( id IN (
         *  (
         *      SELECT `materialId`
         *      FROM `wx_3_material_keyword`
         *      WHERE (  (  (  ( 'll6' LIKE concat('%', keyword, '%') ) ) AND ( `exactMatch` = 0 ) ) OR ( keyword = 'll6' AND exactMatch = 1 ) ) AND ( deleted=0 )  ) ) ) LIMIT 1
         */
		return $result;
	}
	
	private function actionMaterial($material, $message,$us=null) {
		return Module::doModule($material->module, $message, $material, $us);
	}
	
	private function action($keyword, $message) {
//		$material = $this->exist($keyword);
//
//		if (!isset($material)) {
//			Log::write("找不到关键字不处理");
//			return NULL;
//		}
//
//        return $this->actionMaterial((object)$material, $message);

        $arr_material = $this->exist($keyword, $message->indMediaId);
        if (empty($arr_material)) {
            Log::write("找不到关键字不处理");
			return NULL;
        }

        $arr_result = [];
        foreach ($arr_material as $k => $material) {
            $material = (object)$material;

            $result = $this->actionMaterial($material, $message);

            array_push($arr_result, $result);
        }

		return $arr_result;
	}
}

$module = new keywordModule();
Module::addModule($module);
?>
